package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.SheetExceptionInfoAdapter;
import com.xn.app.muying.bean.SheetException_two;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * Created by Administrator on 2017/1/5.
 */
public class SheetExceptionInfoActivity extends BaseActivity implements View.OnClickListener {

    private ListView lv;
    //加载框
    AlertDialog dialog;
    //数据库
    private DBManager db = null;
    private SheetExceptionInfoAdapter adapter;
private ArrayList<SheetException_two> list_two;
    private String reporterCategoryDisplayName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exception);
        db = new DBManager(this);
        initView();
    }

    private void initView() {
        TextView title_name = (TextView) findViewById(R.id.title_name);
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        TextView count = (TextView) findViewById(R.id.activity_exception_count);
        TextView look = (TextView) findViewById(R.id.activity_exception_look);
        lv = (ListView) findViewById(R.id.activity_exception_lv);
        adapter = new SheetExceptionInfoAdapter(SheetExceptionInfoActivity.this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!list_two.get(i).getStatus().equals("0")) {
                    Intent intent = new Intent();
                    intent.putExtra("reporterCategoryDisplayName",reporterCategoryDisplayName );
                    intent.putExtra("chineseName",list_two.get(i).getChineseName());
                    intent.putExtra("statusDescription",list_two.get(i).getStatusDescription());
                    intent.putExtra("introduction",list_two.get(i).getIntroduction());
                    intent.putExtra("observationFocus",list_two.get(i).getObservationFocus());
                    intent.putExtra("conservationFocus",list_two.get(i).getConservationFocus());
                    intent.putExtra("unusualCircumstances",list_two.get(i).getUnusualCircumstances());
                    intent.setClass(SheetExceptionInfoActivity.this,SheetExceptionReasonActivity.class);
                    startActivity(intent);
                }
            }
        });
        title_name.setText("已解读");
        count.setText(getIntent().getStringExtra("exceptionCount") + "项异常指标");
        img_back.setOnClickListener(this);
        look.setOnClickListener(this);
        if (NetworkUtil.isNetworkAvailable(SheetExceptionInfoActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(SheetExceptionInfoActivity.this, R.layout.dialog_loading);
            getExceptionInfo(getIntent().getStringExtra("id"));
        } else {
            ToastUtil.showToast(SheetExceptionInfoActivity.this, R.string.no_network_hint);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.activity_exception_look:
                Intent intent = new Intent();
                intent.putExtra("id", getIntent().getStringExtra("id"));
                intent.setClass(SheetExceptionInfoActivity.this, LookSheetActivity.class);
                startActivity(intent);
                break;
        }
    }


    private void getExceptionInfo(final String id) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.SheetInfo(id)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    onJsonData(msg.obj.toString());
                    break;
                case 1:
                    ToastUtil.showToast(SheetExceptionInfoActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    private void onJsonData(String bobys) {
        try {
            JSONObject jsonObject = new JSONObject(bobys);
            reporterCategoryDisplayName = jsonObject.optString("reporterCategoryDisplayName");
            JSONArray results = jsonObject.getJSONArray("results");
//            ArrayList<SheetExceptionBean> list_one = new ArrayList<>();
            list_two = new ArrayList<>();
            for (int i = 0; i < results.length(); i++) {
                JSONObject object = results.getJSONObject(i);
                String chineseName = object.optString("chineseName");
                String status = object.optString("status");
                String statusDescription = object.optString("statusDescription");
                String introduction = object.optString("introduction");
                String observationFocus = object.optString("observationFocus");
                String conservationFocus = object.optString("conservationFocus");
                String unusualCircumstances = object.optString("unusualCircumstances");
                String nomalRange = object.optString("nomalRange");
                if(!status.equals("0")){
                    SheetException_two sheetException_two = new SheetException_two();
                    sheetException_two.setChineseName(chineseName);
                    sheetException_two.setStatus(status);
                    sheetException_two.setStatusDescription(statusDescription);
                    sheetException_two.setIntroduction(introduction);
                    sheetException_two.setObservationFocus(observationFocus);
                    sheetException_two.setConservationFocus(conservationFocus);
                    sheetException_two.setUnusualCircumstances(unusualCircumstances);
                    sheetException_two.setNomalRange(nomalRange);
                    list_two.add(sheetException_two);
                }
            }
//            SheetExceptionBean sheetExceptionBean = new SheetExceptionBean();
//            sheetExceptionBean.setReporterCategoryDisplayName(reporterCategoryDisplayName);
//            sheetExceptionBean.setList(list_two);
//            list_one.add(sheetExceptionBean);
//            Log.i("list_one", list_one + "");
            adapter.getData(list_two);
            lv.setVisibility(ListView.VISIBLE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
